<template>
  <section class="app-main">
    <!-- 基本信息+请求地址 -->
    <el-card class="box-card">
      <div slot="header" class="clearfixFist">
        <span>基本信息</span>
        <el-button v-if="this.$parent.$checkRoles([20201])" plain style="margin-left:20px;"
                   :type="infoDisabled?'primary':'success'"
                   @click="editInformation(infoDisabled)" size="mini">{{ infoDisabled ? '修改' : '保存' }}
        </el-button>
        <el-button style="margin-left:20px;" type="success" @click="excilOut(3)" size="mini">导出接口结构</el-button>
      </div>
      <div class="item">
        <el-form label-position="right" label-width="100px" :model="InitInfo">
          <el-form-item label="选择环境">
            <el-select @visible-change="visChange" size="small" v-model="requestHost" placeholder="请选择">
              <el-option
                  v-for="item in host"
                  :key="item.host"
                  :label="item.name"
                  :value="item.host">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="请求地址">
            {{ requestHost + InitInfo.request_url }}
          </el-form-item>
          <el-form-item label="请求类型">
            {{ 'HTTP' }}
          </el-form-item>
          <el-form-item label="接口名称">
            <el-input style="width:200px;min-width: 350px" size="small" :disabled="infoDisabled" v-model="InitInfo.title"></el-input>
          </el-form-item>
          <el-form-item label="接口地址">
            <!-- {{InitInfo.request_url}} -->
            <el-input style="width:200px;min-width: 350px" size="small" :disabled="infoDisabled"
                      v-model="InitInfo.request_url"></el-input>
          </el-form-item>
          <el-form-item label="请求方式">
            <!-- {{getRequestMethod(InitInfo.request_method)}} -->
            <el-select size="small" style="min-width: 350px" :disabled="infoDisabled" v-model="InitInfo.request_method" placeholder="请选择">
              <el-option
                  v-for="item in requestMold"
                  :key="item.value"

                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="请求体类型">
            <el-select size="small" style="min-width: 350px" :disabled="infoDisabled" v-model="InitInfo.request_type" placeholder="请选择">
              <el-option
                  v-for="item in requestType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="接口描述">
            <el-input
                type="textarea"
                autosize
                :rows="4"
                style="width:300px;min-width: 350px"
                placeholder="请输入内容"
                :disabled="infoDisabled"
                v-model="InitInfo.remark">
            </el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <!-- MORK表 -->
    <el-card class="margin_top box-card">
      <div slot="header" @click="showRequest = !showRequest" class="clearfix">
        <span>MOCK</span>
        <i :class="showRequest?'el-icon-caret-top':'el-icon-caret-bottom'"></i>
      </div>
      <div v-show="showRequest" class="item">
        <h4 style="padding-bottom:20px;">请求头参数</h4>
        <el-form label-position="right" size="small" label-width="140px" v-if="this&&this.$parent.$checkRoles([50201])">
          <el-form-item v-for="(item,index) in jsonHeaders" :key="index" label="">
            <el-input size="mini" v-model="item.key" style="width:250px;margin: 2px 5px;">
              <template slot="prepend">key</template>
            </el-input> :
            <el-input size="mini" v-model="item.value" style="width:250px;margin: 2px 5px;">
              <template slot="prepend">value</template>
            </el-input>
            <el-button  type="success" @click="add_header" size="mini" icon="el-icon-circle-plus">新增
            </el-button>
            <el-button @click="delete_header(index)" icon="el-icon-remove" type="danger"
                       v-if="(jsonHeaders.length > 1 )" size="mini">删除
            </el-button>
          </el-form-item>
        </el-form>
        <el-form v-else label-position="right" size="small" label-width="140px">
          <el-form-item v-for="(item,index) in jsonHeaders" :key="index" label="">
            key ：
            <el-input v-model="item.key" style="width:200px;"></el-input>
            value ：
            <el-input v-model="item.value" style="width:200px;"></el-input>
          </el-form-item>
        </el-form>

        <h4 style="padding-bottom:20px;">请求参数</h4>
        <el-tabs v-model="activeName" @tab-click="handleClick">

          <!--          表格模式-->
          <el-tab-pane label="表格模式" name="table">
            <div class="padding_margin">
              <div class="item">
                <el-table size="small" :data="requestList" style="width: 100%;margin-bottom: 20px;" row-key="uuidme"
                          :row-class-name="tableRowClassNameMock" border default-expand-all
                          :tree-props="{children: 'children',hasChildren: 'hasChildren'}">
                  <el-table-column label="字段名称" width="400" v-if="this&&this.$parent.$checkRoles([50201])">
                    <template slot-scope="scope">
                      <el-input style="width:200px" size="small"
                                v-model="scope.row.name"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="字段名称" width="400" v-else>
                    <template slot-scope="scope">
                      <el-input disabled style="width:200px" size="small"
                                v-model="scope.row.name"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="字段值">
                    <template slot-scope="scope">
                      <el-input v-if="!scope.row.children && scope.row.type !=7" style="width:200px" size="small"
                                v-model="scope.row.mockValue"></el-input>
                      <div v-if="scope.row.type == 7" class="uploadInfo">
                        <input type="file" id="fileUpload" @change="fileChange($event,scope.row)">
                        <img style="width:100px;height:100px" :src="scope.row.mockValue?scope.row.mockValue:addImg"
                             alt="">
                        <video style="width:100px;height:100px"
                               :src="scope.row.mockValue?scope.row.mockValue:addImg"></video>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="remark" label="说明"></el-table-column>
                  <el-table-column label="操作" width="200" v-if="this&&this.$parent.$checkRoles([50201])">
                    <template slot-scope="scope">
                      <el-button size="mini" @click="add_requestData(requestList,scope.row.uuidme,scope.row)"
                                 type="success">新增
                      </el-button>
                      <el-button size="mini" @click="setDisabled(scope.row)"
                                 :type="scope.row.disabled?'success':'danger'">{{ scope.row.disabled ? '启用' : '禁用' }}
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-tab-pane>


          <el-tab-pane label="json模式" name="json">
            <el-input style="padding-bottom:20px;" type="textarea" placeholder="请输入内容" autosize v-model="request_json"/>
          </el-tab-pane>
        </el-tabs>
        <!-- 返回参数 -->
        <el-button type="primary" @click="sendServeTest()" size="small">发送</el-button>


        <div v-if="newRequestRendData && newRequestRendData.length">
          <el-input style="padding-bottom:20px;" type="textarea" placeholder="请输入内容" autosize
                    v-model="newRequestRendData"/>
        </div>
        <div class="item" style="padding-top:20px">
          <div v-if="requestRendData" style="white-space: pre-line;">
            <json-viewer v-if="this&&this.$parent.$checkRoles([50001])" :expand-depth='5' boxed copyable
                         :value="requestRendData"></json-viewer>
          </div>
        </div>
        <div>
          <el-image
              style="width: 300px; height: 300px;margin-top:20px"
              :src="url"
              v-if="url"
              @error="imgError"
              fit="fill">
            <div slot="error" class="image-slot">
              <!-- 图片展示失败默认为空 -->
            </div>
          </el-image>
        </div>
      </div>
    </el-card>

    <!-- 请求参数详解 -->
    <el-card class="margin_top box-card" v-if="this.$parent.$checkRoles([60001])">
      <div slot="header" class="clearfixFist">
        <span>请求参数</span>
        <div style="padding-top:20px;" v-if="this.$parent.$checkRoles([60201])">
          <div style="padding-bottom:20px;" class="excil" v-if="this.$parent.$checkRoles([60201])">
            <el-button plain size="mini" @click="excilEnter(1)" type="danger">导入请求参数</el-button>
            <el-button plain size="mini" @click="excilOut(1)" type="warning">导出请求参数</el-button>
            <el-button @click="editRequestData" :type="editRequestInfo.type" size="mini">{{ editRequestInfo.title }}
            </el-button>
          </div>
        </div>
      </div>
      <div class="item">
        <div class="request_param_remark">
          <el-form label-position="right" :inline="true" label-width="100px" :model="InitInfo">
            <el-form-item label="请求参数说明">
              <el-input
                  type="textarea"
                  autosize
                  :rows="4"
                  style="width:300px;"
                  placeholder="请输入内容"
                  :disabled="requestRemark.disabled"
                  v-model="InitInfo.request_param_remark">
              </el-input>
            </el-form-item>
            <el-form-item label="" v-if="this.$parent.$checkRoles([60201])">
              <el-button :type="requestRemark.type" @click="editRequestRemark(InitInfo.request_param_remark)"
                         size="small">{{ requestRemark.title }}
              </el-button>
            </el-form-item>
          </el-form>

        </div>
        <el-table
            size="small"
            v-if="unitShow"
            :row-class-name="tableRowClassName"
            :data="renderList"
            style="width: 100%;margin-bottom: 20px;"
            row-key="uuidme"
            border
            default-expand-all
            drag
            :tree-props="{children: 'children',hasChildren: 'hasChildren'}">
          <el-table-column prop="name" label="字段名称" width="400">
            <template slot-scope="scope">
              <span v-if="!editRequestInfo.disable">{{ scope.row.name }}</span>
              <span v-else-if="scope.row.isOtherObject">{{ '' }}</span>
              <el-input style="width:240px;" v-else v-model="scope.row.name"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="类型" width="200">
            <template slot-scope="scope">
              <span v-if="!editRequestInfo.disable">{{ getType(scope.row) }}</span>
              <el-select v-else v-model="scope.row.type" placeholder="请选择">
                <el-option
                    v-for="item in requestKeyTypeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="是否必填">
            <template slot-scope="scope">
              <span v-if="!editRequestInfo.disable">{{ scope.row.required ? '必填' : '非必填' }}</span>
              <el-switch v-else size="small" :active-value="0" :inactive-value="1" v-model="scope.row.required"
                         active-color="#ff4949" inactive-color="#13ce66"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="是否显示">
            <template slot-scope="scope">
              <span v-if="!editRequestInfo.disable">{{ scope.row.show == 1 ? '显示' : '不显示' }}</span>
              <el-switch
                  v-else
                  :active-value="0"
                  :inactive-value="1"
                  size="small"
                  v-model="scope.row.show"
                  active-color="#ff4949"
                  inactive-color="#13ce66">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="说明">
            <template slot-scope="scope">
              <span v-if="!editRequestInfo.disable">{{ scope.row.remark }}</span>
              <span v-else-if="scope.row.isOtherObject"></span>
              <el-input v-else v-model="scope.row.remark"></el-input>
            </template>
          </el-table-column>
          <el-table-column v-if="editRequestInfo.disable" label="操作" width="200">
            <template slot-scope="scope">
              <el-button size="mini" @click="add_requestData(renderList,scope.row.uuidme,scope.row)" type="success">
                新增
              </el-button>
              <el-button size="mini" @click="delete_requestData(renderList,scope.row.uuidme)" type="danger">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <!-- <el-card class="margin_top box-card">
        <h3>MOCK反参</h3>
        <el-input  style="padding-bottom:20px;" type="textarea" placeholder="请输入内容" autosize v-model="inteMockData"/>
        <el-button @click="submitMock" size="small" type="success">提交</el-button>
    </el-card> -->
    <!-- 返回字段说明 -->
    <el-card class="margin_top box-card" v-if="this.$parent.$checkRoles([70001])">
      <div slot="header" class="clearfixFist">
        <span>返回字段说明</span>
        <div style="padding-top:20px;" v-if="this.$parent.$checkRoles([70201])">
          <el-button plain size="mini" @click="excilEnter(2)" type="danger">导入返回参数</el-button>
          <el-button plain size="mini" @click="excilOut(2)" type="warning">导出返回参数</el-button>
          <el-button @click="editResponseData" :type="editResponse.type" size="mini">{{ editResponse.title }}
          </el-button>
          <el-button v-if="this.$parent.$checkRoles([70201])" :type="responseRemark.type" @click="editResponseRemark(InitInfo.response_param_remark)"
                     size="mini">{{ responseRemark.title }}
          </el-button>
        </div>
      </div>
      <div class="item">
        <div class="request_param_remark">
          <el-form label-position="right" :inline="true" label-width="100px" :model="InitInfo">
            <el-form-item label="">
              <div style="width: 300px;display: flex;justify-content: space-between;height: 30px;">
                <h5 style="line-height: 30px;margin: 0;padding: 0;font-size: 13px">返回参数说明</h5>
              </div>
              <p style="font-size: 12px" v-if="responseRemark.disabled">
                {{InitInfo.response_param_remark?InitInfo.response_param_remark:'此接口没有设置任何说明'}}
              </p>
              <el-input
                  type="textarea"
                  autosize
                  v-else
                  :rows="4"
                  size="mini"
                  style="width:300px;margin: 0;padding: 0;"
                  placeholder="请输入内容"
                  :disabled="responseRemark.disabled"
                  v-model="InitInfo.response_param_remark">
              </el-input>
            </el-form-item>
          </el-form>
        </div>
        <h5 style="line-height: 30px;margin: 0;padding: 0;font-size: 13px">返回字段说明</h5>

        <!--        请求table-->
        <el-table
            size="small"
            :row-class-name="tableRowClassNameRes"
            :data="responseData"
            style="width: 100%;margin-bottom: 20px;"
            row-key="uuidme"
            border
            default-expand-all
            :tree-props="{children: 'children',hasChildren: 'hasChildren'}">
          <el-table-column prop="name" label="字段名称" width="400">
            <template slot-scope="scope">
              <span v-if="!editResponse.disable">{{ scope.row.name==='_null'?getType(scope.row):scope.row.name }}</span>
              <el-input style="width:240px;" v-else v-model="scope.row.name"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="类型" width="200">
            <template slot-scope="scope">
              <span v-if="!editResponse.disable">{{ getType(scope.row) }}</span>
              <el-select v-else v-model="scope.row.type" placeholder="请选择">
                <el-option
                    v-for="item in requestKeyTypeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="是否必填">
            <template slot-scope="scope">
              <span v-if="!editResponse.disable">{{ scope.row.required ? '必填' : '非必填' }}</span>
              <el-switch v-else size="small" :active-value="0" :inactive-value="1" v-model="scope.row.required"
                         active-color="#ff4949" inactive-color="#13ce66"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="是否显示">
            <template slot-scope="scope">
              <span v-if="!editResponse.disable">{{ scope.row.show == 1 ? '显示' : '隐藏' }}</span>
              <el-switch
                  v-else
                  :active-value="0"
                  :inactive-value="1"
                  size="small"
                  v-model="scope.row.show"
                  active-color="#ff4949"
                  inactive-color="#13ce66">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="说明">
            <template slot-scope="scope">
              <span v-if="!editResponse.disable">{{ scope.row.remark }}</span>
              <el-input style="width:240px;" v-else v-model="scope.row.remark"></el-input>
            </template>
          </el-table-column>
          <el-table-column v-if="editResponse.disable" label="操作" width="200">
            <template slot-scope="scope">
              <el-button size="small" @click="add_requestData(responseData,scope.row.uuidme,scope.row)" type="success">
                新增
              </el-button>
              <el-button size="small" @click="delete_requestData(responseData,scope.row.uuidme,scope.row)"
                         type="danger">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <el-dialog :before-close="close" :title="newTitle" :visible.sync="newShow">
      <el-form label-position="right" label-width="100px">
        <el-form-item label="">
          <json-viewer :expand-depth='5' v-if="excilOutVal" copyable :value="excilOutVal"></json-viewer>
          <el-input :rows="5" :autosize="{ minRows: 10, maxRows: 4}" v-if="!excilOutVal" type="textarea"
                    placeholder="请输入内容" v-model="excilEnterVal"/>
        </el-form-item>
        <el-form-item label="">
          <el-button :type="responseRemark.type" v-if="!excilOutVal && excilEnterVal" @click="editExcilVal()"
                     size="small">确定
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </section>
</template>

<script>
import addImg from '@/assets/images/upload.svg'
import JsonViewer from 'vue-json-viewer';
import {requestKeyTypeList, requestMold, requestType} from '@/public/dictionaries.js'
import Ptree from './Ptree.vue'
import {GET, POST} from '@/api/request' //request
import {file_base} from '@/public/dense/editImg.js'
import {CONFIG_DATA} from '@/config/index'
import {requestData} from '@/api'
import {filterNull} from '@/public/index'
import {base64_decrypt} from "../../public/dense/base64";

var structure = {
  "root": {
    "name": "Main Level",
    nodes: {
      "node1": {
        "name": "Node 1"
      },
      "node2": {
        "name": "Node 2"
      },
      "node3": {
        "name": "Node 3"
      }
    }
  }
}
export default {
  name: 'appMain',
  data() {
    return {
      content: {},//上下文
      newTitle: '导入',
      newShow: false,
      requestRemark: {
        title: '修改参数说明',
        type: 'primary',
        disabled: true
      },
      responseRemark: {
        title: '修改参数说明',
        type: 'warning',
        disabled: true
      },
      newRequestRendData: '',//返回的串
      infoDisabled: true,
      showRequest: false,//是否展开mock
      requestKeyTypeList: requestKeyTypeList,
      requestMold: requestMold,
      requestType: requestType,
      excilOutVal: '',//导出数据
      editRequestInfo: {
        title: '修改字段说明',
        type: 'primary',
        disable: false
      },//
      editResponse: {
        title: '修改字段说明',
        type: 'primary',
        disable: false
      },
      excilEnterVal: '',
      url: '',
      isShowImg: false,
      addImg: addImg,//图片上传ICON
      imageUrl: '',//文件上传地址
      activeName: 'table',
      request_json: '',
      requestHost: '',//请求一级地址
      host: {},    //地址选择
      requestList: [],//TEST api
      requestTypeArr: [    //请求类型
        {
          value: 0,
          label: 'FormData'
        }, {
          value: 1,
          label: 'Json'
        }, {
          value: 2,
          label: 'File'
        }
      ],
      requestModelArr: [
        {
          value: 0,
          label: 'GET'
        }, {
          value: 1,
          label: 'POST'
        }
      ],//请求方式
      newSendlist: [],//发送
      responseData: [],//mock 请求后接收到的数据
      renderList: [],//渲染请求参数
      requestRendData: {},
      inteMockData: '',//mock参数
      jsonHeaders: [{}],//请求头参数
      unitShow: true,//辅助强制刷新
      // response
      excilType: null,
      mainDisable: false,  //默认是否可以修改
      // requestData:{
      //     type:'',    //请求类型  0form   1json   2文件上传
      //     method:'',  //请求方式
      //     jsonParams:'',//请求参数
      //     jsonHeaders:[],//请求头
      //     fileParamName:'',//文件名
      // },
      testList: [],

      num: 0
    }
  },
  props: {
    /**
     *  @InitInfo    基本信息
     */
    InitInfo: {
      type: Object
    }
  },
  components: {
    JsonViewer, Ptree
  },
  created() {
  },
  mounted: async function () {
    this.host = JSON.parse(localStorage.host)
    this.requestHost = this.host[0].host
    this.content = this
  },
  computed: {},
  methods: {
    //格式回归
    objectIn(indata, fun) {
      //列表
      if (indata instanceof Array) {
        indata.forEach((item) => {
          this.objectIn(item, fun)
        })
      } else if (indata && indata.toString() == '[object Object]') {
        fun(indata)
        let vals = Object.values(indata)
        for (let i = 0; i < vals.length; i++) {
          this.objectIn(vals[i], fun)
        }
      }
    },
    //格式回归
    flybackObject(indata, outdata) {
      //列表
      if (indata instanceof Array) {
        delete indata.uuidme
        indata.forEach((item) => {
          this.flybackObject(item, indata)
        })
      } else if (indata && indata.toString() == '[object Object]') {
        delete indata.uuidme
        //复杂数据isOtherObject回归
        if (Object.keys(indata).indexOf("isOtherObject") != -1) {
          let temp = {}
          indata.children.forEach(i1 => {
            temp[i1.keyNameV1] = i1
            delete temp[i1.keyNameV1].keyNameV1
          })
          delete indata.children
          delete indata.isOtherObject
          Object.assign(indata, temp);
          this.flybackObject(indata, indata)
        } else {
          Object.keys(indata).forEach((item) => {
            //实际Object 操作
            if (item == "keyIsNull") {
              delete indata.keyIsNull
              let tempItem = {}
              Object.keys(indata).forEach(itemKey => {
                tempItem[itemKey] = indata[itemKey]
                delete indata[itemKey]
              })
              delete tempItem.uuidme
              indata._null = tempItem
            } else if (item == "children") {
              if ((indata.children instanceof Array) && indata.children[0] && indata.children[0].keyName) {
                let tempCh = {};
                indata.children.forEach(itemChIn => {
                  tempCh[itemChIn.keyName] = itemChIn
                  delete tempCh[itemChIn.keyName].keyName
                })
                indata.children = tempCh
                this.flybackObject(tempCh, indata)
              }
              this.flybackObject(indata[item], indata)
            } else
              this.flybackObject(indata[item], indata)
          })
        }
      }
    },

    //格式解析
    recursiveObject: function (indata) {
      //列表
      if (indata instanceof Array) {
        indata.forEach((item) => {
          indata.uuidme = this.get_uuid()
          //特殊处理对象
          let hasObjectValue = false;
          let obj = Object.values(item)
          for (let i = 0; i < obj.length; i++) {
            if (obj[i].toString() == "[object Object]") {
              hasObjectValue = true;
              break
            }
          }
          if (hasObjectValue && item.toString() == "[object Object]"
              && Object.keys(item).indexOf("keyIsNull") == -1
              && Object.keys(item).indexOf("children") == -1
              && Object.keys(item).indexOf("java_name") == -1
              && Object.keys(item).indexOf("_null") == -1) {
            console.log("精心处理前：", JSON.stringify(item))

            let keys = Object.keys(item)
            let temp = []
            let pushKeys = []
            keys.forEach(itemV1 => {
              if ((["required", "show", "oldMockValue", "mockValue", "type"].indexOf(itemV1) == -1) || (item[itemV1].toString() == "[object Object]")) {
                item[itemV1]["keyNameV1"] = itemV1
                pushKeys.push(itemV1)
                temp.push(item[itemV1])
              }
            })
            pushKeys.forEach(t1 => {
              delete item[t1]
            })
            item["children"] = temp
            item["isOtherObject"] = true
            item.type = 6
            item.show = 1
            item.required = 1
            console.log("精心处理后：", JSON.stringify(item))
          }
          this.recursiveObject(item)
        })
      } else if (indata.toString() == '[object Object]') {
        if (Object.keys(indata).toString() == "_null") {
          indata._null.keyIsNull = true
          indata._null.type = 4
          indata._null.show = 1
          indata._null.name = ""
          indata._null.remark = ""

          indata.uuidme = this.get_uuid()

          Object.keys(indata._null).forEach(i => {
            indata[i] = indata._null[i]
          })
          console.log("——null处理后", indata._null)
          delete indata._null

          Object.values(indata).forEach(uutem => {
            this.recursiveObject(uutem)
          })
        } else {
          Object.keys(indata).forEach((item) => {
            //实际Object 操作
            indata.uuidme = this.get_uuid()
            if (item == "children") {
              if (indata[item].toString() == '[object Object]' && !(indata[item] instanceof Array)) {
                let temp = [];
                Object.keys(indata[item]).forEach(itema => {
                  if (indata[item][itema]) {
                    if (itema == "_null") {
                      indata[item][itema]["keyIsNull"] = true
                    } else
                      indata[item][itema]["keyName"] = itema
                  }
                  temp.push(indata[item][itema])
                })
                indata[item] = temp
                //继续检索
                this.recursiveObject(indata[item]);
              }
            }
            this.recursiveObject(indata[item])
          })
        }

      }
    },

    //提交mock数据
    async submitMock() {
      let data = {
        responseParamName: this.InitInfo.response_param_name,
        json: this.inteMockData
      }
      let res = await requestData(2, '/updateMock', data)
      this.$message.success('修改成功')
    },
    async excilOut(num) { //导出
      let list
      if (num == 1) {
        list = await requestData(2, '/getRequestParam', {requestParamName: this.InitInfo.request_param_name})
      } else if (num == 2) {
        list = await requestData(2, '/getResponseParam', {responseParamName: this.InitInfo.response_param_name})
      } else {
        list = this.InitInfo
      }
      this.excilOutVal = list
      this.newShow = true
      this.newTitle = '导出'

    },
    async excilEnter(num) { //导入
      this.excilType = num
      let list
      if (num == 1) {
        list = await requestData(2, '/getRequestParam', {requestParamName: this.InitInfo.request_param_name})
      } else {
        list = await requestData(2, '/getResponseParam', {responseParamName: this.InitInfo.response_param_name})
      }
      this.excilEnterVal = JSON.stringify(list)
      this.newShow = true
      this.newTitle = '导入'
    },
    async setDisabled(row) {
      if (row.disabled) {
        this.$set(row, 'disabled', false)
      } else {
        this.$set(row, 'disabled', true)
      }
    },
    async editExcilVal() {
      this.excilEnterVal = JSON.stringify(JSON.parse(this.excilEnterVal))
      if (this.excilType == 1) {
        let sendData = {
          requestParamName: this.InitInfo.request_param_name,
          json: this.excilEnterVal
        }
        let newdata = await POST('/updateRequestParams', sendData)
        let requestResData = await requestData(2, '/getRequestParam', {requestParamName: this.InitInfo.request_param_name})
        this.renderData(requestResData)
      } else {
        let sendData = {
          responseParamName: this.InitInfo.response_param_name,
          json: this.excilEnterVal
        }
        await POST('/updateResponseParams', sendData)
        let responseData = await requestData(2, '/getResponseParam', {responseParamName: this.InitInfo.response_param_name})
        this.getResponse(responseData)
      }
      this.close()
    },
    close() {
      this.newShow = false
      this.excilOutVal = null
      this.excilEnterVal = null
    },
    //修改请求参数说明
    async editRequestRemark(remark) {
      if (this.requestRemark.disabled) {
        //可以修改
        this.requestRemark = {
          disabled: false,
          title: '保存',
          type: 'success'
        }
      } else {

        console.log("editRequestRemark 解析处理前：", JSON.stringify(this.InitInfo))

        this.flybackObject(this.InitInfo)

        console.log("editRequestRemark 解析处理前：", JSON.stringify(this.InitInfo))


        //保存
        let data = {
          controllerName: this.InitInfo.controller_name,
          javaName: this.InitInfo.javaName,
          json: JSON.stringify(this.InitInfo)
        }

        // return
        console.log("update")

        await requestData(2, '/updateInteface', data)
        this.requestRemark = {
          disabled: true,
          title: '修改',
          type: 'primary'
        }
      }
    },
    //修改返回参数说明
    async editResponseRemark(remark) {
      if (this.responseRemark.disabled) {
        //可以修改
        this.responseRemark = {
          disabled: false,
          title: '保存',
          type: 'success'
        }
      } else {
        //保存
        let data = {
          controllerName: this.InitInfo.controller_name,
          javaName: this.InitInfo.javaName,
          json: JSON.stringify(this.InitInfo)
        }
        await requestData(2, '/updateInteface', data)
        this.responseRemark = {
          disabled: true,
          title: '修改参数说明',
          type: 'danger'
        }
      }
    },
    //剔除空
    deleteNullData() {

    },
    async mockData() {
      sessionStorage.mock = true
      let res = await GET('/easyapi/doc/mock?path=' + this.InitInfo.request_url, {}, '')
      this.requestRendData = res
      sessionStorage.mock = false
    },
    visChange(flag) {    //下拉框触发时
      if (flag) {
        this.host = JSON.parse(localStorage.host)
      }
    },
    async editInformation() {  //修改基本信息
      if (this.infoDisabled) {
        this.infoDisabled = false
      } else {

        let data = {
          controllerName: this.InitInfo.controller_name,
          javaName: this.InitInfo.javaName,
          json: JSON.stringify(this.InitInfo)
        }
        await requestData(2, '/updateInteface', data)
        this.infoDisabled = true
      }
    },
    tableRowClassName({row, rowIndex}) {    //隐藏非必填 请求参数
      if (!row.show && !this.editRequestInfo.disable) {
        return 'warning-row';
      } else {
        return 'success-row';
      }
    },
    tableRowClassNameRes({row, rowIndex}) {
      if (!row.show && !this.editResponse.disable) {
        return 'warning-row';
      } else {
        return 'success-row';
      }
    },
    tableRowClassNameMock({row, rowIndex}) {    //隐藏非必填 MOCK表
      if (row.type == 7 && !row.disabled) return 'success-row'
      if (!row.show && !row.disabled) {
        return 'warning-row';
      } else if (!row.disabled) {
        return 'success-row';
      } else if (row.disabled) {
        return 'disabled-row'
      }
    },
    setJsonHeaders(arr) {
      let obj = {}
      arr.map(item => {
        obj[item.key] = item.value
      })
      return obj
    },
    async editResponseData() {
      if (this.editResponse.type == 'primary') {
        this.editResponse = {type: 'success', title: '保存', disable: true}
      } else {
        let data = JSON.parse(JSON.stringify(this.responseData))
        let res = data//await this.sendData(data)

        console.log("editResponseData 解析处理前：", JSON.stringify(this.res))

        this.flybackObject(res)

        console.log("editResponseData 解析处理前：", JSON.stringify(this.res))

        let newData = {}
        res.map(item => {
          newData[item.name] = item
        })
        let sendData = {
          responseParamName: this.InitInfo.response_param_name,
          json: JSON.stringify(newData)
        }


        await POST('/updateResponseParams', sendData)
        let responseData = await requestData(2, '/getResponseParam', {responseParamName: this.InitInfo.response_param_name})
        this.getResponse(responseData)
      }
    },
    async editRequestData() {  //请求参数列表
      if (this.editRequestInfo.type == 'primary') {
        this.editRequestInfo = {type: 'success', title: '保存', disable: true}
      } else {
        let data = JSON.parse(JSON.stringify(this.renderList))
        let res = data//await this.sendData(data)
        console.log("editRequestData 解析处理前：", JSON.stringify(this.res))

        this.flybackObject(res)

        console.log("editRequestData 解析处理前：", JSON.stringify(this.res))

        let newData = {}
        res.map(item => {
          newData[item.name] = item
        })

        let sendData = {
          requestParamName: this.InitInfo.request_param_name,
          json: JSON.stringify(newData)
        }

        await POST('/updateRequestParams', sendData)
        let requestResData = await requestData(2, '/getRequestParam', {requestParamName: this.InitInfo.request_param_name})
        this.renderData(requestResData)
      }
    },
    createdInit(type) {  //数据初始化 editResponseData
      this.url = ''
      this.isShowImg = false
      this.newRequestRendData = ''
      if (!type) {
        this.requestRendData = {}
      }
    },
    async fileChange(e, row) {
      let file = e.target.files[0]
      if (!file) return
      let imgUrl = await file_base(file)
      this.$set(row, 'mockValue', imgUrl)
    },
    //切换模式
    async handleClick(tab, event) {
      if (tab.name == 'json') {
        let res = JSON.parse(JSON.stringify(this.requestList))
        console.log("转JSON前：", res)
        res = res.filter(item => item.show)
        res = await this.edit_tureQuest(res, {})
        this.$nextTick(() => {
          this.request_json = JSON.stringify(res, null, 4)
        })
        console.log("转JSON：", res)

      }
    },
    async getResponse(data) {
      if (data instanceof Array) data = data[0]
      let arr = await this.obj_arr(data)
      this.responseData = arr//await this.getData(arr)
      /**
       * 可乐 debug 新增
       */
      // for (let i = 0; i < this.responseData.length; i++)
      console.log("getResponse 解析处理前：", JSON.stringify(this.responseData))

      this.recursiveObject(this.responseData)

      console.log("getResponse 解析处理前：", JSON.stringify(this.responseData))

      //END
      this.editResponse = {type: 'primary', title: '修改', disable: false}
    },
    //数组转对象
    arr_obj(arr) {
      let obj = {}
      arr.forEach(item => {
        obj[item.name] = item
      })
      return obj
    },
    //对象转数组
    obj_arr(obj) {
      let arr = []
      for (let prop in obj) {
        arr.push(obj[prop])
      }
      return arr
    },
    isHaveFile(list) {
      let name, fileBase
      let arr = JSON.parse(JSON.stringify(list))
      arr.forEach((item, index) => {
        if (item.type == 7) {
          name = item.name
          fileBase = item.mockValue
          arr.splice(index, 1)
        } else if (item.disabled) {
          arr.splice(index, 1)
        }
      })
      return {name: name, fileBase: fileBase, list: arr}
    },
    chooseRequestMold(value) {   //获取请求方式
      let arr = this.requestMold
      for (let i = 0; i <= arr.length; i++) {
        if (arr[i].value == value) {
          return arr[i].label
        }
      }
    },
    async sendServeTest() {    //请求参数 testApi

      console.log("点击了发送1")

      let mockShow = this.host.filter(item => item.host == this.requestHost)
      console.log("点击了发送1")

      if (mockShow[0].name == 'mock') {
        this.mockData()
      } else {
        let urlType = CONFIG_DATA.Content_Type_status
        let getData = await this.isHaveFile(this.requestList)

        let res = await this.edit_tureQuest(getData.list, {})
        res = filterNull(res)
        let data = {
          url: this.requestHost + this.InitInfo.request_url,
          method: this.chooseRequestMold(this.InitInfo.request_method),
          type: this.InitInfo.request_type,
          jsonParams: this.activeName == 'table' ? JSON.stringify(res) : this.request_json,
          jsonHeaders: JSON.stringify(this.setJsonHeaders(this.jsonHeaders))
        }

        if (getData.fileBase) {
          let formdata = new FormData()
          for (let key in data) {
            formdata.append(key, data[key])
          }
          CONFIG_DATA.Content_Type_status = 2
          let file = await dataURItoBlob(getData.fileBase)
          formdata.append('file', file)
          formdata.append('fileParamName', getData.name)
          data = formdata
        }
        let newRes = await POST('/doUrl', data)

        base64_decrypt(newRes).then(success => {
          this.requestRendData = JSON.parse(success)
          this.newRequestRendData = JSON.stringify(this.requestRendData)
        }).catch(err => {
          this.url = "data:image/jpeg;base64," + newRes
        })
        CONFIG_DATA.Content_Type_status = urlType
      }
    },
    imgError() { //图片加载失败的回调
      this.isShowImg = true
    },
    //新增header头
    add_header() {
      this.jsonHeaders.push({})
    },
    //删除header头
    delete_header(index) {
      this.jsonHeaders.splice(index, 1)
    },
    //处理接口请求的的相关数据
    edit_tureQuest(arr, data, type) {
      console.log("临时测试3", arr)
      arr.forEach((item, index) => {
      })
      arr.forEach((item, index) => {
        // console.log(item.name)
        if (!item.show || item.disabled) {
          // arr.splice(index,1);
        } else if (item.type == 5) {
          data[item.name] = []
          //内容不足
          this.edit_tureQuest(item.children, data[item.name], 5)
        } else if (item.type == 6) {

          data[item.name] = {}
          // if(!item.isOtherObject){
          //   this.edit_tureQuest(item.children, data[item.name], 6)
          // }else{
          this.edit_tureQuest(item.children, data[item.name], 6)
          // }
        } else if (type == 5) {
          if (!item.name) {
            data.push(item.mockValue ? item.mockValue : "")
          } else {
            let newData = {}
            newData[item.name] = item.mockValue ? item.mockValue : ""
            data.push(newData)
          }
        } else if (item.type == 8) {
          data[item.name] = {}
          this.edit_tureQuest(item.children, data[item.name], 6)
        } else if (item.type == 9) {
          // data[item.name] = [{}]
          data[item.name] = []

          for (let i = 0; i < item.children.length; i++) {
            data[item.name].push({})
            this.edit_tureQuest(item.children[Object.keys(item.children)[i]].children, data[item.name][i], 6)
          }
          // this.edit_tureQuest(item.children, data[item.name], 6)
        } else {
          // this.$set(data,item.name,item.mockValue?item.mockValue:'')
          data[item.name] = item.mockValue ? item.mockValue : ''
        }
      });
      console.log(data)
      return data
    },
    async renderData(data, type) {   //初始化当前组件
      if (type) {
        this.renderList = data.requestList
        // for (let i = 0; i < this.renderList.length; i++)
        this.recursiveObject(this.renderList)
        this.request_json = data.request_json
        this.inteMockData = data.inteMockData
        this.requestRendData = data.requestRendData
        this.requestList = await JSON.parse(JSON.stringify(this.renderList))
        this.editRequestInfo = {type: 'primary', title: '修改字段说明', disable: false}
      } else {
        this.activeName = 'table'

        let arr = await this.obj_arr(data)
        this.renderList = arr//await this.getData(arr)
        /**
         * 可乐 debug 新增
         */
        // for (let i = 0; i < this.renderList.length; i++)
        console.log("renderData解析处理前：", JSON.stringify(this.renderList))

        this.recursiveObject(this.renderList)

        console.log("renderData解析处理前：", JSON.stringify(this.renderList))

        //END

        this.requestList = await JSON.parse(JSON.stringify(this.renderList))

        this.editRequestInfo = {type: 'primary', title: '修改', disable: false}
      }
      this.objectIn(this.requestList, function (obj) {
        if (obj && obj.show && obj.show == 0)
          obj.show = 1
      })
    },
    getInteMockDataData(data) {
      this.inteMockData = data
    },
    //回显数据
    getType(row) {
      switch (row.type) {
        case 1: //0全部
          return '整数'
        case 2: //1GET
          return '数字'
        case 3: //2POST
          return '布尔'
        case 4: //2POST
          return '字符串'
        case 5: //2POST
          return '基本数组'
        case 6: //2POST
          return '对象'
        case 7:
          return '文件'
        case 8:
          return 'MAP'
        case 9:
          return '对象数组'
      }
    },
    getBlacklist(row) {
      return [
        "java_name",
        "",
        "",
        "",
        "",
        "",
      ]
    },
    //处理服务端的返回字段说明
    async getData(arr) {
      if (arr.length) {
        arr.forEach(async (item, index) => {
          if (item.type == 5 && item.children.length && !arr[index].children[0].name) {
            let newObject = arr[index].children[0]
            let newArr = await this.obj_arr(newObject)
            arr[index].children = newObject
            this.getData(arr[index].children)
          } else if (item.type == 8 && item.children) {
            let newObject = arr[index].children
            let newArr = await this.obj_arr(newObject)
            arr[index].children = newObject
            // this.getData(arr[index].children)
          } else if (item.type == 9 && item.children.length) {
            let newObject = arr[index].children[0]
            let newArr = await this.obj_arr(newObject)
            arr[index].children = newArr
          } else if (item.type == 6) {
            arr[index].children = await this.obj_arr(arr[index].children)
            this.getData(item.children)
          } else if (item.children && item.children.length) {
            this.getData(item.children)
          }
        })
        return arr
      } else {
        return arr
      }
    },
    //处理发送给服务端的数据
    async sendData(arr) {
      if (arr.length) {
        arr.forEach((item, index) => {
          if (item.type == 5 && item.children.length) {
            let childArr = arr[index].children
            arr[index].children = []
            arr[index].children[0] = childArr
            this.sendData(arr[index].children)
          } else if (item.type == 6 && item.children.length) {
            let childArr = arr[index].children
            arr[index].children = {}
            childArr.map(item => {
              arr[index].children[item.name] = item
            })
            this.sendData(arr[index].children)
          } else if (item.type == 9 && item.children.length) {
            let childArr = arr[index].children
            arr[index].children = [{}]
            childArr.map(item => {
              arr[index].children[0][item.name] = item
            })
            this.sendData(arr[index].children)
          }
        })
        return arr
      } else {
        return arr
      }
    },
    //将拿到的参数转为JSON格式体 进行接口测试
    /**
     *  0全部
     *  1GET
     *  2POST
     */
    getRequestMethod(type) {  //获取请求方式
      switch (type) {
        case 0: //0全部
          return 'all'
        case 1: //1GET
          return 'GET'
        case 2: //2POST
          return 'POST'
      }
    },
    /**
     *     0form
     *     1json
     *     2文件上传
     */
    getRequestType(type) {   //请求体类型
      switch (type) {
        case 0: //0全部
          return 'formData'
        case 2: //1GET
          return 'JSON格式'
        case 3: //2POST
          return '文件上传'
      }
    },
    add_requestData(data, id, lineData) {
      this.set_recursion(data, id, 0, lineData.type)
    },
    delete_requestData(data, id) {
      // this.requestList.splice(index,1)
      this.set_recursion(data, id, 1)
    },

    getInsertTemplate(type) {
      let base = {
        show: 1,
        required: 1,
        uuid: this.get_uuid(),
        uuidme: this.get_uuid(),
        mockValue: ''
      }
      switch (type) {
        case 1 :
        case 2 :
        case 3 :
        case 4 :
        case 7 :
          return Object.assign({
            type: 4,
            name: 'number',
          }, base);
        case 5 :
          return Object.assign({
            type: 5,
            children: [
              {
                show: 1,
                type: 4,
                mockValue: "",
                keyIsNull: true,
                uuid: "" + this.get_uuid(),
                uuidme: "" + this.get_uuid(),
                required: 1
              }
            ],
          }, base);
        case 6 :
        case 8 :
          return Object.assign({
            name: 'name',
            type: 6,
            children: [
              {
                name: "key1",
                show: 1,
                type: 4,
                mockValue: "",
                uuid: "" + this.get_uuid(),
                uuidme: "" + this.get_uuid(),
                required: 1
              }
            ],
          }, base);
        case 9 :
          return Object.assign({
            type: 9,
            children: [
              {
                show: 1,
                mockValue: "",
                type: 4,
                uuid: "" + this.get_uuid(),
                uuidme: "" + this.get_uuid(),
                required: 1
              }
            ],
          }, base);
      }
    },
    get_uuid() {
      let s = [];
      let hexDigits = "0123456789abcdef";
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = "";

      return s.join("");
    },
    test(data, selectType) {
      let choose = {
        uuidme: this.get_uuid(),
        show: 1,
        required: 1,
        mockValue: ''
      }
      let addData = {}
      if (selectType) {
        addData = this.getInsertTemplate(selectType)
      } else addData = choose
      let that = this
      // this.objectIn(addData,function (item) {
      //   item.uuidme = that.get_uuid()
      // })
      data.push(addData)

      console.log("插上数据的对象UUIDME:", data.uuidme)
      console.log("插上数据的对象UUIDME:", data)

      //强制重绘
      this.$forceUpdate()
      this.unitShow = false;
      this.$nextTick(() => {
        this.unitShow = true;
      })
    }
    ,
    set_recursion(data, id, type, selectType) {   //递归修改数据
      //0新增 1删除
      let that = this
      console.log(type)
      console.log(selectType)
      console.log(data)
      data.forEach((item, index) => {
            if (item.uuidme == id) {
              if (type == 0) {
                if (data instanceof Array) {
                  that.test(data, selectType)
                } else {
                }
              } else {
                data.splice(index, 1)
                //强制重绘
                this.$forceUpdate()
                this.unitShow = false;
                this.$nextTick(() => {
                  this.unitShow = true;
                })
              }
            } else {
              if (item.children && item.children.length) {
                that.set_recursion(item.children, id, type, selectType)
              }
            }
          }
      )

    },
    // searchData(childId){
    //     if(o.nodes != undefined){
    //         for(n in o.nodes){
    //             o.nodes[n].parent = o;
    //             this.setParent(o.nodes[n]);
    //         }
    //     }
    // }
  }
}
</script>

<style lang="scss" scoped>
.app-main {
  min-height: calc(100vh - 50px);
  position: relative;
  overflow: hidden;
  background: #ECF0F5;
  /*height: 840px;*/
  overflow: auto;
  padding: 20px;

  .inputData {
    width: 160px;
  }

  .margin_top {
    margin-top: 20px;
  }

  .padding_margin {
    padding-bottom: 16px;
  }

  .uploadInfo {
    width: 100px;
    height: 100px;
    position: relative;

    #fileUpload {
      width: 100px;
      height: 100px;
      position: absolute;
      opacity: 0;
    }
  }

  .clearfix {
    display: flex;
    justify-content: space-between;
    cursor: pointer;

    .el-icon-caret-bottom, .el-icon-caret-top {
      font-size: 30px;
      color: red;
    }
  }
}
</style>
